<template>
  <div class="app-container">
    <el-row :gutter="20" class="header">
      <el-col :span="5">
        <el-input placeholder="请输入用户名..." v-model="queryForm.username"
        clearable></el-input>
      </el-col>
      <el-col :span="5">
        <el-input placeholder="请输入手机号..." v-model="queryForm.phonenumber"
        clearable></el-input>
      </el-col>
      <el-col :span="4">
        <el-select v-model="queryForm.is_active" placeholder="用户状态" clearable>
          <el-option label="正常" :value="true"></el-option>
          <el-option label="禁用" :value="false"></el-option>
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-select v-model="queryForm.user_from" placeholder="用户来源" clearable>
          <el-option label="本地" :value="1"></el-option>
          <el-option label="LDAP" :value="2"></el-option>
        </el-select>
      </el-col>
      <el-col :span="6">
        <el-button type="primary" :icon="Search" @click="initUserList">搜索</el-button>
        <el-button type="success" :icon="Plus" @click="handleDialogValue()">新增</el-button>
      </el-col>
    </el-row>
    <el-row :gutter="20" style="margin-bottom: 10px;">
      <el-col :span="24">
        <el-popconfirm title="您确定批量删除选中用户吗？" @confirm="handleDeleteBatch">
          <template #reference>
            <el-button type="danger" :disabled="delBtnStatus" :icon="Delete">批量删除</el-button>
          </template>
        </el-popconfirm>
      </el-col>
    </el-row>
    <el-table :data="tableData" stripe style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="avatar" label="头像" width="80" align="center">
        <template v-slot="scope">
          <img :src="getServerUrl()+'media/userAvatar/'+scope.row.avatar"
          width="50" height="50"/>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="100"
      align="center"/>
      <el-table-column prop="nick_name" label="用户昵称" width="100"
      align="center"/>
      <el-table-column prop="roleList" label="拥有角色" width="200" align="center">
        <template v-slot="scope">
          <el-tag size="small" type="warning" v-for="item in scope.row.roleList"> {{ item.name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="200" align="center"/>
      <el-table-column prop="phonenumber" label="手机号" width="120"
      align="center"/>
      <el-table-column prop="user_from" label="用户来源" width="100" align="center">
        <template v-slot="scope">
          <el-tag v-if="scope.row.user_from === 1" type="success" size="small">本地</el-tag>
          <el-tag v-else-if="scope.row.user_from === 2" type="info" size="small">LDAP</el-tag>
          <el-tag v-else type="warning" size="small">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="is_active" label="状态？" width="200" align="center">
        <template v-slot="{row}">
          <el-switch v-model="row.is_active" @change="statusChangeHandle(row)"
          active-text="正常"
          inactive-text="禁用" :active-value="true" :inactive-value="false">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="200"
      align="center"/>
      <el-table-column prop="last_login" label="最后登录时间" width="200"
      align="center"/>
      <el-table-column prop="remark" label="备注"/>
      <el-table-column prop="action" label="操作" width="400" fixed="right"
      align="center">
        <template v-slot="scope">
          <el-button type="primary" :icon="Tools"
          @click="handleRoleDialogValue(scope.row.id,scope.row.roleList)">分配角色
          </el-button>
          <el-popconfirm v-if="scope.row.is_staff==false" title="您确定要对这
          个用户重置密码吗？"
          @confirm="handleResetPassword(scope.row.id)">
          <template #reference>
            <el-button type="warning" :icon="RefreshRight">重置密码</el-button>
          </template>
          </el-popconfirm>
          <el-button type="primary" v-if="scope.row.is_staff==false" :icon="Edit"
          @click="handleDialogValue(scope.row.id)"></el-button>
          <el-popconfirm v-if="scope.row.is_staff==false" title="您确定要删除这条记录吗？" @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button type="danger" :icon="Delete"/>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
  </el-table>
  <el-pagination
    v-model:currentPage="queryForm.page"
    v-model:page-size="queryForm.page_size"
    :page-sizes="[5, 10, 15, 20]"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    />
    <Dialog v-model="dialogVisible" :dialogVisible="dialogVisible" :id="id" :dialogTitle="dialogTitle"
            @initUserList="initUserList"></Dialog>
    <RoleDialog v-model="roleDialogVisible" :roleDialogVisible="roleDialogVisible" :id="id" :sysRoleList="sysRoleList"
            @initUserList="initUserList"></RoleDialog>
  </div>
  </template>

<script setup>
import {ref} from 'vue'
import requestUtil, {getServerUrl} from '@/util/request'
import {ElMessage} from 'element-plus'
import { Search, Tools, RefreshRight, Edit, Delete,Plus } from '@element-plus/icons-vue'
import Dialog from './components/dialog.vue'
import RoleDialog from './components/roleDialog.vue'

const tableData = ref([])
const total = ref(0)
const queryForm = ref({
  username: '',
  phonenumber: '',
  is_active: undefined,
  user_from: undefined,
  page: 1,
  page_size: 10
})

const dialogVisible = ref(false)

const dialogTitle = ref("")

const id = ref(-1)

const delBtnStatus = ref(true)

const multipleSelection = ref([])

const sysRoleList = ref([])

const roleDialogVisible = ref(false)

const initUserList = async () => {
  try {
    if (queryForm.value.username) {
      queryForm.value.page=1
    }
    const res = await requestUtil.get('system/user/', queryForm.value)
    tableData.value = res.results
    total.value = res.count
  } catch (error) {
    console.error('获取用户列表失败', error)
    ElMessage.error('获取用户列表失败')
  }
}


const handleSizeChange = (pageSize) => {
  queryForm.value.page_size = pageSize
  initUserList()
}

const handleCurrentChange = (pageNum) => {
  queryForm.value.page = pageNum
  initUserList()
}

const statusChangeHandle = (row) => {
  // 拼接 RESTful 风格的 URL
  let url = `system/user/${row.id}/`;
  requestUtil.patch(url, {id: row.id, is_active: row.is_active})
  .then(res => {
    try { 
      ElMessage.success('状态修改成功')
    } catch (error) {
      ElMessage.error('状态修改失败')
    }
  })
}

const handleDialogValue = (userId) => {
  if (userId) {
    id.value = userId;
    dialogTitle.value = "用户"
  }else {
    id.value = -1;
    dialogTitle.value = "用户添加"
  }
  dialogVisible.value = true
}

const handleDelete = (userId) => {
    if (userId) {
      requestUtil.del(`system/user/${userId}/`)
      .then(res => {
        try { 
          ElMessage.success('删除成功')
          initUserList()
        } catch (error) {
          ElMessage.error('删除失败')
        }
      })
    }
}

const handleSelectionChange = (val) => {
  console.log("勾选了")
  console.log(val)
  multipleSelection.value = val
  delBtnStatus.value = val.length == 0
}

const handleDeleteBatch = () => {
  if (multipleSelection.value.length > 0) {
    const userIds = multipleSelection.value.map(item => item.id)
    requestUtil.del('system/user/batch_delete/', { ids: userIds })
      .then(res => {
        ElMessage.success('删除成功')
        initUserList()
      })
      .catch(() => {
        ElMessage.error('删除失败')
      })
  }
}

const handleResetPassword = (userId) => {
  if (userId) {
    requestUtil.patch(`system/user/${userId}/`, {password: 'YGreTh59cIPN'})
    .then(res => {
        ElMessage.success('重置密码成功')
      }).catch(error => {
        ElMessage.error('重置密码失败')
      })
  }
}

const handleRoleDialogValue = (userId, roleList) => {
  console.log("roleList：", roleList)
  console.log("id:", id)
  id.value = userId;
  sysRoleList.value = roleList;
  roleDialogVisible.value = true
}

initUserList()
</script>


<style lang="scss" scoped>
.header {
  padding-bottom: 16px;
  box-sizing: border-box;
}
.el-pagination {
  float: right;
  padding: 20px;
  box-sizing: border-box;
  }

::v-deep th.el-table__cell {
    word-break: break-word;
    background-color: #f8f8f9 !important;
    color: #515a6e;
    height: 40px;
    font-size: 13px;
  }
.el-tag--small {
    margin-left: 5px;
  }
</style>
